package com.shycloud.mido.opter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shycloud.mido.common.api.constants.ShoppingStockConstants;
import com.shycloud.mido.common.core.exception.BusinessException;
import com.shycloud.mido.common.core.util.R;
import com.shycloud.mido.common.security.service.ShyUser;
import com.shycloud.mido.common.security.util.SecurityUtils;
import com.shycloud.mido.common.util.NetworkUtil;
import com.shycloud.mido.common.util.SnowFlakeUtil;
import com.shycloud.mido.member.api.entity.BasicGoodsCategory;
import com.shycloud.mido.member.api.entity.BasicGoodsInfo;
import com.shycloud.mido.opter.api.entity.StockDeviceInfo;
import com.shycloud.mido.opter.api.entity.StockExchangeGoods;
import com.shycloud.mido.opter.api.entity.StockProcessDetail;
import com.shycloud.mido.opter.api.entity.StockQuantity;
import com.shycloud.mido.opter.api.entity.StockSaleOrder;
import com.shycloud.mido.opter.api.entity.StockSaleOrderDetail;
import com.shycloud.mido.opter.api.entity.StockWarehouseDetail;
import com.shycloud.mido.opter.api.vo.GenBatchUdidVO;
import com.shycloud.mido.opter.api.vo.StockProcessDetailVO;
import com.shycloud.mido.opter.api.vo.StockSaleOrderDetailVO;
import com.shycloud.mido.opter.api.vo.StockSaleOrderVO;
import com.shycloud.mido.opter.api.vo.StockWarehouseDetailVO;
import com.shycloud.mido.opter.api.vo.inner.OrderUdidVO;
import com.shycloud.mido.opter.mapper.BasicGoodsCategoryMapper;
import com.shycloud.mido.opter.mapper.BasicGoodsInfoMapper;
import com.shycloud.mido.opter.mapper.StockDeviceInfoMapper;
import com.shycloud.mido.opter.mapper.StockExchangeGoodsMapper;
import com.shycloud.mido.opter.mapper.StockProcessDetailMapper;
import com.shycloud.mido.opter.mapper.StockQuantityMapper;
import com.shycloud.mido.opter.mapper.StockSaleOrderDetailMapper;
import com.shycloud.mido.opter.mapper.StockSaleOrderMapper;
import com.shycloud.mido.opter.mapper.StockWarehouseDetailMapper;
import com.shycloud.mido.opter.service.StockOrderService;
import com.shycloud.mido.organ.api.feign.RemoteOrganService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * @author Xiaoxing Yu
 * @date 2020/9/24
 **/
@Slf4j
@Service
@AllArgsConstructor
public class StockOrderServiceImpl extends ServiceImpl<StockSaleOrderMapper, StockSaleOrder> implements StockOrderService {

	/** 销售单出货单Mapper */
	private final StockSaleOrderMapper saleOrderMapper;
	/** 销售单详情出货单Mapper */
	private final StockSaleOrderDetailMapper saleOrderDetailMapper;
	/** 库存Mapper */
	private final StockQuantityMapper stockQuantityMapper;
	/** UDID设备Mapper */
	private final StockDeviceInfoMapper deviceInfoMapper;
	/** 商品信息Mapper */
	private final BasicGoodsInfoMapper goodsInfoMapper;
	/** 商品分类Mapper */
	private final BasicGoodsCategoryMapper categoryMapper;
	/** 库存维修处理Mapper */
	private final StockProcessDetailMapper processMapper;
	/** 仓库库存明细Mapper */
	private StockWarehouseDetailMapper warehouseDetailMapper;
	/** 机构模块 feign service */
	private final RemoteOrganService organService;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Map addSaleOrder(StockSaleOrderVO saleOrderVO) {

		//初始化结果集
		Map returnMap = new HashMap();

		try {

			StockSaleOrder entity = new StockSaleOrder();

			if (!StringUtils.isBlank(saleOrderVO.getOutPreDate())) {
				entity.setOutPreDate(toLocalDateTime(
						new SimpleDateFormat("yyyy-MM-dd").parse(saleOrderVO.getOutPreDate())));
			}

			BeanUtils.copyProperties(saleOrderVO, entity);
			entity.setCommitStatus(ShoppingStockConstants.ORDER_UNCOMMITED);
			entity.setOutType(ShoppingStockConstants.OUT_TYPE_SALE);
			Long orderNo = (saleOrderVO.getOrderNo() != null) ? saleOrderVO.getOrderNo()
					: generateOrderNo();
			entity.setOrderNo(orderNo);
			entity.setCreateTime(LocalDateTime.now());
			entity.setOutStatus(ShoppingStockConstants.STATUS_NOT_OUT);

			if (saleOrderVO.getWarehouseId() != null) {
				entity.setWarehouseId(saleOrderVO.getWarehouseId());
			}

			int outAmount = 0;

			if (saleOrderVO.getDetailList() != null && saleOrderVO.getDetailList().size() != 0) {
				List<StockSaleOrderDetailVO> detailList = saleOrderVO.getDetailList();
				for (StockSaleOrderDetailVO detailVO : detailList) {
					StockSaleOrderDetail detail = new StockSaleOrderDetail();
					BeanUtils.copyProperties(detailVO, detail);
					Integer goodsId = detailVO.getGoodsId();
					BasicGoodsInfo goodsInfo = goodsInfoMapper.selectOne(
							new QueryWrapper<BasicGoodsInfo>().eq("id", goodsId));
					detail.setType(goodsInfo.getUseType());
					detail.setOrderNo(orderNo);
					if (saleOrderDetailMapper.insert(detail) != 1) {
						throw new BusinessException("添加销售单失败");
					}
					outAmount += detail.getQuantity();
				}
			}

			entity.setOutAmount(outAmount);
			if (saleOrderMapper.insert(entity) != 1) {
				throw new BusinessException("添加销售单失败!");
			}

			returnMap.put("orderNo", orderNo);
		} catch (BusinessException e) {
			log.error(e.getMessage(), e);
			throw e;
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			throw new BusinessException("添加销售单失败!");
		}

		return returnMap;
	}

	@Override
	public Boolean addSaleOrderDetail(StockSaleOrderDetailVO detailVO) {
		StockSaleOrderDetail entity = new StockSaleOrderDetail();
		BeanUtils.copyProperties(detailVO, entity);

		int insertResult = saleOrderDetailMapper.insert(entity);

		return insertResult == 1 ? true : false;
	}

	@Override
	public Boolean editSaleOrder(StockSaleOrderVO editVO) {
		StockSaleOrder existingOrder = null;

		try {
			existingOrder = saleOrderMapper.selectOne(
					new QueryWrapper<StockSaleOrder>().eq("order_no", editVO.getOrderNo()));

			if (editVO.getContact() != null) {
				existingOrder.setContact(editVO.getContact());
			}
			if (editVO.getAddress() != null) {
				existingOrder.setAddress(editVO.getAddress());
			}
			if (editVO.getCreatedBy() != null) {
				existingOrder.setCreatedBy(editVO.getCreatedBy());
			}
			if (editVO.getComments() != null) {
				existingOrder.setComments(editVO.getComments());
			}
			if (editVO.getWarehouseId() != null) {
				existingOrder.setWarehouseId(editVO.getWarehouseId());
			}
			existingOrder.setUpdateTime(LocalDateTime.now());

			if (StringUtils.isNotBlank(editVO.getOutPreDate())) {
				existingOrder.setOutPreDate(toLocalDateTime(
						new SimpleDateFormat("yyyy-MM-dd").parse(editVO.getOutPreDate())));
			}

			//删除结果可以为0
			saleOrderDetailMapper.delete(
					new QueryWrapper<StockSaleOrderDetail>()
							.eq("order_no", editVO.getOrderNo()));

			//更新插入新的GoodsList
			for (StockSaleOrderDetailVO detailVO : editVO.getDetailList()) {
				StockSaleOrderDetail detail = new StockSaleOrderDetail();
				BeanUtils.copyProperties(detailVO, detail);
				Integer goodsId = detailVO.getGoodsId();
				BasicGoodsInfo goodsInfo = goodsInfoMapper.selectOne(
						new QueryWrapper<BasicGoodsInfo>().eq("id", goodsId));
				detail.setType(goodsInfo.getUseType());
				if (saleOrderDetailMapper.insert(detail) != -1) {
					throw new BusinessException("编辑销售单失败");
				}
			}
		} catch (BusinessException e) {
			log.error(e.getMessage(), e);
			throw e;
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			throw new BusinessException("编辑销售单失败");
		}

		return true;
	}

	@Override
	public Boolean commitSaleOrder(StockSaleOrderVO saleOrderVO) {
		StockSaleOrder existingOrder = null;
		try {
			existingOrder = saleOrderMapper.selectOne(
					new QueryWrapper<StockSaleOrder>().eq("order_no", saleOrderVO.getOrderNo()));

			if (existingOrder == null) {
				throw new BusinessException("未找到对应订单号!");
			}

			existingOrder.setCommitStatus(ShoppingStockConstants.ORDER_COMMITED);
			existingOrder.setCommitTime(LocalDateTime.now());

			if (saleOrderMapper.updateById(existingOrder) != 1) {
				throw new BusinessException("提交销售单失败!");
			}
		} catch (BusinessException e) {
			log.error(e.getMessage(), e);
			throw e;
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			throw new BusinessException("提交销售单失败");
		}

		return true;
	}

	@Override
	public Boolean deleteSaleOrder(StockSaleOrderVO saleOrderVO) {
		return saleOrderMapper.deleteById(saleOrderVO.getOrderNo()) == 1 ? true : false;
	}

	@Override
	public List<StockSaleOrder> getSaleOrders(String commitStatus, String outStatus) {
		return saleOrderMapper.selectList(
				new QueryWrapper<StockSaleOrder>()
						.eq("commit_status", commitStatus)
						.eq("out_status", outStatus));
	}

	@Override
	public IPage<StockSaleOrderVO> pageSaleOrders(Page page, String commitStatus,
			String outStatus, String createdBy,
			String outType, String startDate,
			String endDate, String searchName,
			String comments, String processStatus, String orderNo) {

		IPage<StockSaleOrderVO> returnPage = saleOrderMapper.pageSaleOrders(page, commitStatus,
				outStatus, createdBy, outType,
				startDate, endDate, searchName, comments, processStatus, orderNo);

		List<StockSaleOrderVO> returnList = returnPage.getRecords();

		for (StockSaleOrderVO orderVO : returnList) {
			List<StockSaleOrderDetail> detailList = saleOrderDetailMapper.selectList(
					new QueryWrapper<StockSaleOrderDetail>().eq("order_no", orderVO.getOrderNo()));

			List<StockSaleOrderDetailVO> returnVOList = new ArrayList();
			for (StockSaleOrderDetail detail : detailList) {
				StockSaleOrderDetailVO detailVO = new StockSaleOrderDetailVO();
				BeanUtils.copyProperties(detail, detailVO);
				detailVO.setGoodsName(
						goodsInfoMapper.selectOne(
								new QueryWrapper<BasicGoodsInfo>()
										.eq("id", detail.getGoodsId())).getName());
				returnVOList.add(detailVO);
			}

			orderVO.setDetailList(returnVOList);

			OrderUdidVO udidVO = new OrderUdidVO();

			List<StockDeviceInfo> deviceInfoList = deviceInfoMapper.selectList(
					new QueryWrapper<StockDeviceInfo>().eq("order_no", orderVO.getOrderNo()));

			List<String> saleUdidList = new ArrayList<>();
			List<String> rentUdidList = new ArrayList<>();

			for (StockDeviceInfo deviceInfo : deviceInfoList) {
				if ("1".equals(deviceInfo.getType())) {
					rentUdidList.add(deviceInfo.getUdid());
				} else if ("2".equals(deviceInfo.getType())) {
					saleUdidList.add(deviceInfo.getUdid());
				}
			}

			udidVO.setRentUdidList(rentUdidList);
			udidVO.setSaleUdidList(saleUdidList);

			orderVO.setOrderUdids(udidVO);
		}

		return returnPage;
	}

	/**
	 * 出库订单
	 *
	 * @param saleOrderVO
	 * @return
	 * @author nianhua.jiang
	 * @date 2021/1/20 14:18
	 **/
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean sendOutOrder(StockSaleOrderVO saleOrderVO) {
		try {
			Integer optId = saleOrderVO.getOptId();
			Integer orgId = saleOrderVO.getOrgId();
			Integer distId = saleOrderVO.getDistId();

			StockSaleOrder orderEntity = saleOrderMapper.selectOne(
					new QueryWrapper<StockSaleOrder>()
							.eq(StockSaleOrder.ORDER_NO, saleOrderVO.getOrderNo()));

			if (orderEntity == null) {
				throw new BusinessException("未找到该订单！");
			}
			if (orderEntity.getOutStatus().equals(ShoppingStockConstants.STATUS_OUT)) {
				throw new BusinessException("该订单已发货，请勿重复发货!");
			}

			if (orderEntity.getCommitStatus().equals(ShoppingStockConstants.ORDER_UNCOMMITED)) {
				throw new BusinessException("该订单还未提交确认，请先提交订单!");
			}

			orderEntity.setOutStatus(ShoppingStockConstants.STATUS_OUT);
			orderEntity.setCreateTime(LocalDateTime.now());
			orderEntity.setOutTime(LocalDateTime.now());
			if (saleOrderVO.getCourier() != null) {
				orderEntity.setCourier(saleOrderVO.getCourier());
			}
			if (saleOrderVO.getDeliveryOrder() != null) {
				orderEntity.setDeliveryOrder(saleOrderVO.getDeliveryOrder());
			}

			if (saleOrderMapper.updateById(orderEntity) != 1) {
				throw new BusinessException("发货失败!");
			}

			Integer warehouseId = orderEntity.getWarehouseId();

			//************************* 更新 udid 状态 START 2021/01/20 *******************************//
			for (String udid : saleOrderVO.getSaleUdidList()) {

				StockDeviceInfo stockDeviceInfo = new StockDeviceInfo();
				// 发货状态 0-未发货 1-发货 2-作废
				stockDeviceInfo.setStatus("1");
				// 商品 ID - 这里只是永久硬件条
				stockDeviceInfo.setGoodsId(1);
				// 运营商 ID
				stockDeviceInfo.setOptId(optId);
				// 机构 ID
				stockDeviceInfo.setOrgId(orgId);
				// 经销商ID
				stockDeviceInfo.setDistId(distId);
				// 订单编号
				stockDeviceInfo.setOrderNo(saleOrderVO.getOrderNo());
				// 永久设备
				stockDeviceInfo.setType("2");
				//状态- 未激活
				stockDeviceInfo.setActiveStatus("1");

				deviceInfoMapper.update(stockDeviceInfo,
						new QueryWrapper<StockDeviceInfo>().eq("udid", udid));
			}
			//************************* 更新 udid 状态 E N D 2021/01/20 *******************************//

			List<StockSaleOrderDetail> detailList = saleOrderDetailMapper.selectList(
					new QueryWrapper<StockSaleOrderDetail>()
							.eq(StockSaleOrder.ORDER_NO, saleOrderVO.getOrderNo()));

			//减少总部商品对应库存，增加对应运营商库存
			for (StockSaleOrderDetail detailVO : detailList) {
				Integer goodsId = detailVO.getGoodsId();
				Integer delta = detailVO.getQuantity();

				//总部减库存，更新stock_quantity表
				StockQuantity hdQuantityEntity =
						stockQuantityMapper.selectOne(
								new QueryWrapper<StockQuantity>()
										.eq("opt_id", ShoppingStockConstants.HEADQUARTER_OPT_ID)
										.eq("goods_id", goodsId));

				if (hdQuantityEntity == null) {
					throw new BusinessException("总部暂无库存，发货失败！");
				}

				if (hdQuantityEntity.getGoodsQuantity() - delta < 0) {
					throw new BusinessException("总部库存不足，发货失败！");
				}

				Integer curHdQuantity = hdQuantityEntity.getGoodsQuantity() - delta;
				hdQuantityEntity.setGoodsQuantity(curHdQuantity);

				//更新 goodsInfo 表
				BasicGoodsInfo goodsEntity = goodsInfoMapper.selectOne(
						new QueryWrapper<BasicGoodsInfo>().eq("id", goodsId));
				goodsEntity.setStockQuantity(curHdQuantity);

				//运营商加库存
				StockQuantity clientQuantityEntity =
						stockQuantityMapper.selectOne(
								new QueryWrapper<StockQuantity>()
										.eq(
												optId != null ? "opt_id" : "org_id",
												optId != null ? optId : orgId)
										.eq("goods_id", goodsId));

				if (clientQuantityEntity == null) {
					clientQuantityEntity = new StockQuantity();
					if (optId != null) {
						clientQuantityEntity.setOptId(optId);
					} else if (orgId != null) {
						clientQuantityEntity.setOrgId(orgId);
					}
					clientQuantityEntity.setGoodsId(goodsId);
					clientQuantityEntity.setGoodsQuantity(0 + delta);
				} else {
					clientQuantityEntity
							.setGoodsQuantity(clientQuantityEntity.getGoodsQuantity() + delta);
				}

				//处理仓库库存逻辑
				StockWarehouseDetail detailEntity = warehouseDetailMapper.selectOne(
						new QueryWrapper<StockWarehouseDetail>().eq("goods_id", goodsId)
								.eq("warehouse_id", warehouseId));
				if (detailEntity != null && detailEntity.getGoodsAmount() >= delta) {
					detailEntity.setGoodsAmount(detailEntity.getGoodsAmount() - delta);
					detailEntity.setAccuOutAmount(detailEntity.getAccuOutAmount() + delta);
				} else {
					throw new BusinessException("发货失败！所选对应仓库库存不足!");
				}
				warehouseDetailMapper.updateById(detailEntity);
			}

			// 押金发货的场合，需要自动激活，租赁一年
			if ("3".equals(saleOrderVO.getOutType())) {
				List<String> saleUdidList = saleOrderVO.getSaleUdidList();
				if (saleUdidList.size() != 1) {
					throw new BusinessException("押金发货的场合只允许发货一个硬件！");
				}
				String udid = saleUdidList.get(0);
				organService.activateByDurationMini(udid, "2", "1", 1, "", null, orgId, null, 3);
			}

		} catch (Exception e) {

		}
		return true;
	}

	@Override
	public List<Map<String, String>> generateBatchUdid(GenBatchUdidVO batchVO) {
		List<Map<String, String>> returnList = new ArrayList<>();

		List<StockDeviceInfo> existings = deviceInfoMapper.selectList(
				new QueryWrapper<StockDeviceInfo>().eq("order_no", batchVO.getOrderNo())
						.eq("type", batchVO.getType()));

		if (existings != null && existings.size() == batchVO.getCount()) {
			for (StockDeviceInfo deviceInfo : existings) {
				Map udidMap = new HashMap();
				udidMap.put("udid", deviceInfo.getUdid());
				returnList.add(udidMap);
			}
			return returnList;
		}

		for (int i = 0; i < batchVO.getCount(); i++) {
			Map udidMap = new HashMap();
			String genCode = generateCode(batchVO.getType());

			//进行验重
			StockDeviceInfo deviceInfo = deviceInfoMapper.selectOne(
					new QueryWrapper<StockDeviceInfo>().eq("udid", genCode));
			if (deviceInfo != null) {
				i--;
				continue;
			}

			StockDeviceInfo stockDeviceInfo = new StockDeviceInfo();
			stockDeviceInfo.setUdid(genCode);
			//未发货
			stockDeviceInfo.setStatus("0");
			//设置订单号
			stockDeviceInfo.setOrderNo(batchVO.getOrderNo());
			//商品ID
			stockDeviceInfo.setGoodsId(batchVO.getGoodsId());
			//类型 1-租赁 2-永久
			stockDeviceInfo.setType(batchVO.getType());

			if (batchVO.getOptId() != null) {
				stockDeviceInfo.setOptId(batchVO.getOptId());
			} else if (batchVO.getOrgId() != null) {
				stockDeviceInfo.setOrgId(batchVO.getOrgId());
			}

			deviceInfoMapper.insert(stockDeviceInfo);

			udidMap.put("udid", genCode);
			returnList.add(udidMap);
		}
		return returnList;
	}

	@Override
	public StockDeviceInfo getUdidInfo(String udid) {
		StockDeviceInfo deviceInfo = deviceInfoMapper.selectOne(new QueryWrapper<StockDeviceInfo>().eq("udid", udid));

		if (deviceInfo == null) {
			throw new BusinessException("该Udid设备码不存在！");
		}

		return deviceInfo;
	}

	@Override
	public Boolean deleteUdidByOrderNo(GenBatchUdidVO batchUdidVO) {
		return deviceInfoMapper.delete(new QueryWrapper<StockDeviceInfo>()
				.eq("order_no", batchUdidVO.getOrderNo())) == 1 ? true : false;
	}

	/**
	 * 商品维修处理
	 *
	 * @return
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean processService(StockProcessDetailVO processVO) {
		try {
			Long orderNo = processVO.getOrderNo();
			if (orderNo == null) {
				throw new BusinessException("订单号不能为空!");
			}

			if (processVO.getScrapedAmount() != null && processVO.getScrapedAmount() > 0) {
				//减总部库存
				BasicGoodsInfo goodsInfo = goodsInfoMapper.selectOne(
						new QueryWrapper<BasicGoodsInfo>().eq("id", processVO.getGoodsId()));
				goodsInfo.setStockQuantity(
						goodsInfo.getStockQuantity() - processVO.getScrapedAmount());
				if (goodsInfoMapper.updateById(goodsInfo) != 1) {
					throw new BusinessException("处理失败！");
				}

				StockQuantity stockQuantity =
						stockQuantityMapper.selectOne(
								new QueryWrapper<StockQuantity>()
										.eq("opt_id", ShoppingStockConstants.HEADQUARTER_OPT_ID)
										.eq("goods_id", processVO.getGoodsId()));
				stockQuantity.setGoodsQuantity(
						stockQuantity.getGoodsQuantity() - processVO.getScrapedAmount());
				if (stockQuantityMapper.updateById(stockQuantity) != 1) {
					throw new BusinessException("处理失败");
				}

				//减少发货仓库库存
				StockSaleOrder orderEntity = saleOrderMapper.selectOne(
						new QueryWrapper<StockSaleOrder>().eq(
								"order_no", processVO.getOrderNo()));
				if (orderEntity == null) {
					throw new BusinessException("根据订单号未查询到对应订单!");
				}

				//设置已处理状态
				orderEntity.setProcessStatus("1");
				if (saleOrderMapper.updateById(orderEntity) != 1) {
					throw new BusinessException("处理失败!");
				}

				Integer warehouseId = orderEntity.getWarehouseId();

				StockWarehouseDetail warehouseDetail = warehouseDetailMapper.selectOne(
						new QueryWrapper<StockWarehouseDetail>()
								.eq("warehouse_id", warehouseId)
								.eq("goods_id", processVO.getGoodsId()));

				if (warehouseDetail == null) {
					StockWarehouseDetail detail = new StockWarehouseDetail();
					detail.setGoodsId(processVO.getGoodsId());
					detail.setScrapedAmount(processVO.getScrapedAmount());
					if (warehouseDetailMapper.insert(detail) != 1) {
						throw new BusinessException("处理失败!");
					}
				} else {
					warehouseDetail.setScrapedAmount(
							warehouseDetail.getScrapedAmount() + processVO.getScrapedAmount());
					if (warehouseDetailMapper.updateById(warehouseDetail) != 1) {
						throw new BusinessException("处理失败!");
					}
				}
			}

			StockProcessDetail processEntity = new StockProcessDetail();

			String dateStr = processVO.getProcessDateStr();
			processEntity.setProcessDate(
					toLocalDateTime(new SimpleDateFormat("yyyy-MM-dd").parse(dateStr)));
			//TODO 暂定都为维修调拨
			processEntity.setProcessType("1");

			BeanUtils.copyProperties(processVO, processEntity);

			if (processMapper.insert(processEntity) != 1) {
				throw new BusinessException("处理失败！");
			}
		} catch (BusinessException e) {
			log.error(e.getMessage(), e);
			throw e;
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			throw new BusinessException("处理失败!");
		}

		return true;
	}

	@Override
	public IPage<StockSaleOrderVO> pageProcessList(Page page, String commitStatus, String outStatus,
			String createdBy, String outType, String startDate,
			String endDate, String searchName, String comments) {
		IPage<StockSaleOrderVO> returnPage = saleOrderMapper.pageProcessList(page, commitStatus,
				outStatus, createdBy, outType,
				startDate, endDate, searchName, comments);

		List<StockSaleOrderVO> returnList = returnPage.getRecords();

		for (StockSaleOrderVO orderVO : returnList) {
			//剔除的
		}

		return returnPage;
	}

	/**
	 * 分页获取商品维修处理记录
	 *
	 * @param page
	 * @param startDate
	 * @param endDate
	 * @param createdBy
	 * @param processType
	 * @param warehouseId
	 * @param goodsName
	 * @param comments
	 * @return
	 */
	@Override
	public IPage<StockProcessDetailVO> pageProcessDetail(Page page,
			String startDate, String endDate,
			String createdBy, String processType,
			Integer warehouseId, String goodsName,
			String comments) {
		return processMapper.pageProcessDetail(page, startDate, endDate, createdBy, processType,
				warehouseId, goodsName, comments);
	}

	@Override
	public List<BasicGoodsInfo> getHardwareGoods() {
		String categoryName = ShoppingStockConstants.INTELLIENT_EQUIP;
		BasicGoodsCategory category = categoryMapper.selectOne(
				new QueryWrapper<BasicGoodsCategory>()
						.eq(ShoppingStockConstants.COLUMN_NAME, categoryName));

		return goodsInfoMapper.selectList(
				new QueryWrapper<BasicGoodsInfo>().eq("category_id", category.getId()));
	}

	@Override
	public IPage<StockWarehouseDetailVO> pageGoodsStockAmount(Page page,
			Integer warehouseId, Integer goodsId,
			Integer categoryId) {
		return warehouseDetailMapper.pageGoodsStockAmount(page, warehouseId, goodsId, categoryId);
	}

	@Override
	public Map getAllStockInfo() {
		Map returnMap = new HashMap();
		Integer totalQuantity = 0;
		Integer exchangeQuantity = 0;

		List<StockWarehouseDetail> detailList =
				warehouseDetailMapper.selectList(
						new QueryWrapper<StockWarehouseDetail>());

		for (StockWarehouseDetail detail : detailList) {
			totalQuantity += detail.getGoodsAmount();
		}

		List<StockSaleOrder> orderList = saleOrderMapper
				.selectList(new QueryWrapper<StockSaleOrder>()
						.eq("commit_status", ShoppingStockConstants.ORDER_COMMITED)
						.eq("out_type", ShoppingStockConstants.OUT_TYPE_EXCHANGE));

		for (StockSaleOrder order : orderList) {
			exchangeQuantity += order.getOutAmount();
		}

		returnMap.put("totalQuantity", totalQuantity);
		returnMap.put("exchangeQuantity", exchangeQuantity);

		return returnMap;
	}

	private String generateCode(String type) {
		//生成码例子: "JM20091AH8"
		StringBuffer sb = new StringBuffer("JM");

		//添加发货年后两位, 2020年，则为20
		sb.append(new SimpleDateFormat("yyyy").format(new Date())).substring(2, 4);
		//添加发货月
		sb.append(new SimpleDateFormat("MM").format(new Date()));
		//添加类型	1-租赁 2-永久
		sb.append(type);

		//生成随机3位 大写字母+数字随机组合, 唯一不可重复，去掉字母O

		StringBuffer randTail = new StringBuffer();
		for (int i = 0; i < 3; i++) {
			int rand = new Random().nextInt(26) + 65;
			if (rand == 79) {
				i--;
				continue;
			} else {
				randTail.append((char) rand);
			}
		}

		sb.append(randTail);

		return sb.toString();
	}

	private static Long generateOrderNo() {
		//雪花算法生成全局唯一orderNo
		Integer machineId = ShoppingStockConstants.getConsistentHash(NetworkUtil.getHostIp());
		long orderNo = new SnowFlakeUtil(1, machineId).nextId();
		log.info("购买生成订单编号为: " + orderNo);
		return orderNo;
	}

	private LocalDateTime toLocalDateTime(Date date) {
		Instant instant = date.toInstant();
		ZoneId zoneId = ZoneId.systemDefault();

		return instant.atZone(zoneId).toLocalDateTime();
	}

	@Override
	@Transactional()
	public List<String> genUDID(String type, Integer count) {

		//记录生成人员
		ShyUser user = SecurityUtils.getUser();
		String username = user.getUsername();

		List<String> resUdids = new ArrayList<>(count);

		for (int i = 0; i < count; i++) {
			String code = this.generateCode(type);
			while (deviceInfoMapper.selectList(new QueryWrapper<StockDeviceInfo>().eq("udid", code))
					.size() > 0) {
				code = this.generateCode(type);
			}
			StockDeviceInfo stockDeviceInfo = new StockDeviceInfo();
			stockDeviceInfo.setUdid(code);
			stockDeviceInfo.setGenUsername(username);
			//未发货
			stockDeviceInfo.setStatus("0");
			//类型 1-租赁 2-永久
			stockDeviceInfo.setType(type);
			deviceInfoMapper.insert(stockDeviceInfo);
			resUdids.add(code);
		}
		return resUdids;
	}

	@Override
	@Transactional()
	public Boolean stopUdid(String udid, String orderNo) {

		//---- 硬件状态更新 ------//
		StockDeviceInfo deviceInfo = deviceInfoMapper.selectOne(new QueryWrapper<StockDeviceInfo>().eq("udid", udid));
		//修改状态为【已作废/停用】
		deviceInfo.setStatus("2");
		int updDev = deviceInfoMapper.update(deviceInfo, new QueryWrapper<StockDeviceInfo>().eq("udid", udid));

		//----- 商品出货单更新 -----//
		QueryWrapper<StockSaleOrder> qwSaleOrder = new QueryWrapper<StockSaleOrder>().eq("order_no", orderNo);
		StockSaleOrder stockSaleOrder = saleOrderMapper.selectOne(qwSaleOrder);
		stockSaleOrder.setStatus("1");
		stockSaleOrder.setStopTime(LocalDateTime.now());
		int updSaleOrder = saleOrderMapper.update(stockSaleOrder, qwSaleOrder);

		if (updDev == 1 && updSaleOrder == 1) {
			return true;
		} else {
			throw new BusinessException("停用失败，请联系后台管理员");
		}
	}
}
